﻿using QWManage.DAL;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlackList.YiYeSync
{
    public class RecordsDAL : SqlDAL
    {
        public RecordsDAL()
        {
            TableName = "Records";
        }
        public List<RecordInfo> GetRecordInfosQWIDNull()
        {
            List<RecordInfo> list = new List<RecordInfo>();
            SqlConnection conn = new SqlConnection(SQLCON);
            try
            {
                string sql = $"select * from {TableName} where QWID is null";
                SqlCommand cmd = new SqlCommand(sql, conn);
                conn.Open();
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        RecordInfo obj = GetRecordInfo(reader);
                        list.Add(obj);
                    }
                }
                return list;
            }
            finally
            {
                conn.Close();
            }
        }

        public bool UpdateQWID(int id, string qwid)
        {
            string sql = $"Update {TableName} set " +
                $"QWID=@QWID " +
                $"where id=@id";
            using (SqlConnection conn = new SqlConnection(SQLCON))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.Add(GetStringSqlParameter("@qwid", qwid));
                cmd.Parameters.Add(GetIntSqlParameter("@id", id));
                return cmd.ExecuteNonQuery() == 1;
            }
        }

        private RecordInfo GetRecordInfo(SqlDataReader reader)
        {
            RecordInfo obj = new RecordInfo();
            obj.ID = ReadInt(reader, "ID");
            obj.QWID = ReadString(reader, "QWID");
            obj.CreatedAt = ReadString(reader, "CreatedAt");
            obj.UpdatedAt = ReadString(reader, "UpdatedAt");
            obj.ExternalUseridAddAt = ReadString(reader, "ExternalUseridAddAt");
            obj.WechatAppletUserid = ReadString(reader, "WechatAppletUserid");
            return obj;
        }
    }
}
